const { MongoClient, ServerApiVersion } = require('mongodb');
const uri = `mongodb+srv://test01:Password01@cluster0.4pymu.mongodb.net?retryWrites=true&w=majority`;


let client;

const init = () => {
    client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
    console.log('正在连接数据库')
    client.connect(err => {
        if (err) {
            console.log('连接失败：', err);
        } else {
            console.log('连接成功，可以获取表数据');
        }
        
    //   const collection = client.db("sample_analytics").collection("accounts");
    //   collection.find().toArray((err, res) => {
    //     console.log('err', err)
    //       console.log('res', res)
    //       client.close();
    //       console.log('关闭连接');
    //   })
    // perform actions on the collection object
    });
}

const getUser = (username) => {
    return new Promise((resolve, reject) => {
        client.db("test").collection("user").find({username}).toArray((err, res) => {
            if (err) reject(err);
            resolve(res);
        });
        
    })
}

const createUser = (user) => {
    return new Promise((resolve, reject) => {
        client.db("test").collection("user").insertOne(user, function(err, res) {
            if (err) reject(err);
            resolve()
            console.log("文档插入成功");
        });
    })
}



module.exports = {
    init,
    createUser,
    getUser,
}

